/**
 * @file service_route.cpp
 * @brief API网关服务路由管理实现
 * @details 实现了服务路由的匹配、重写、管理等核心功能
 *
 * 主要功能：
 * 1. 路径匹配：支持精确匹配、前缀匹配、正则表达式匹配
 * 2. 路径重写：支持前缀去除和目标路径前缀添加
 * 3. 路由管理：支持路由的增删改查、配置加载保存
 * 4. 配置解析：支持YAML、JSON、ENV等多种配置格式
 *
 * @author 29108
 * @date 2025/7/15
 */

#include "core_services/api_gateway/service_route.h"
#include "common/logger/logger.h"
#include "common/config/config_manager.h"
#include <regex>
#include <algorithm>
#include <fstream>
#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <cctype>

namespace core_services {
    namespace api_gateway {

        /**
         * @brief 检查请求路径是否匹配当前路由规则
         * @param path 请求路径，如 "/api/users/123"
         * @return 匹配返回true，否则返回false
         *
         * @details 支持三种匹配模式：
         * 1. EXACT: 精确匹配，路径必须完全相同
         * 2. PREFIX: 前缀匹配，支持通配符(*)和目录匹配
         * 3. REGEX: 正则表达式匹配，支持复杂的路径模式
         */
        bool ServiceRoute::matchPath(const std::string &path) const {
            // 根据匹配类型进行不同的匹配逻辑
            switch (match_type) {
                case MatchType::EXACT:
                    // 精确匹配：路径必须完全相同
                    // 例如：pattern="/api/users" 只匹配 "/api/users"
                    return path_pattern == path;

                case MatchType::PREFIX:
                    // 前缀匹配：路径以指定前缀开始
                    if (path_pattern.empty()) return false;

                    // 处理通配符前缀匹配（如 /api/users/*）
                    // 例如：pattern="/api/users/*" 匹配 "/api/users/123", "/api/users/profile" 等
                    if (path_pattern.back() == '*') {
                        std::string prefix = path_pattern.substr(0, path_pattern.length() - 1);
                        return path.find(prefix) == 0;
                    }

                    // 处理以/结尾的前缀匹配
                    // 例如：pattern="/api/users/" 匹配 "/api/users/123" 但不匹配 "/api/users"
                    if (path_pattern.back() == '/') {
                        return path.find(path_pattern) == 0;
                    }

                    // 普通前缀匹配
                    // 例如：pattern="/api" 匹配 "/api/users", "/api/orders" 等
                    return path.find(path_pattern) == 0;

                case MatchType::REGEX:
                    // 正则表达式匹配：使用正则表达式进行复杂匹配
                    // 例如：pattern="^/api/users/\d+$" 只匹配 "/api/users/数字"
                    try {
                        std::regex pattern(path_pattern);
                        return std::regex_match(path, pattern);
                    } catch (const std::regex_error& e) {
                        LOG_ERROR("路径模式正则表达式错误: " + path_pattern + " -> " + e.what());
                        return false;
                    }

                default:
                    // 默认使用精确匹配作为后备方案
                    return path_pattern == path;
            }
        }

        /**
         * @brief 重写请求路径，用于路径转换和代理
         * @param original_path 原始请求路径，如 "/api/users/123"
         * @return 重写后的路径，如 "/v1/users/123"
         *
         * @details 路径重写过程：
         * 1. 前缀去除：如果启用strip_path_prefix，去除匹配的路径前缀
         * 2. 前缀添加：如果设置了target_path_prefix，添加目标路径前缀
         *
         * 示例：
         * - 原始路径: "/api/users/123"
         * - 路由模式: "/api/*", strip_path_prefix=true, target_path_prefix="/v1"
         * - 重写结果: "/v1/users/123"
         */
        std::string ServiceRoute::rewritePath(const std::string &original_path) const {
            std::string result = original_path;

            // 步骤1：如果启用了前缀去除，去除匹配的路径前缀
            if (strip_path_prefix && !path_pattern.empty()) {
                // 只对前缀匹配类型进行前缀去除
                if (match_type == MatchType::PREFIX) {
                    std::string prefix = path_pattern;

                    // 处理末尾斜杠："/api/" -> "/api"
                    if (prefix.back() == '/') {
                        prefix.pop_back(); // 移除末尾的斜杠
                    }

                    // 如果路径以前缀开始，则去除前缀
                    if (result.find(prefix) == 0) {
                        result = result.substr(prefix.length());

                        // 确保结果路径以/开头
                        if (result.empty() || result[0] != '/') {
                            result = "/" + result;
                        }
                    }
                }
            }

            // 步骤2：添加目标路径前缀
            if (!target_path_prefix.empty()) {
                std::string prefix = target_path_prefix;

                // 避免双斜杠："/v1/" + "/users" -> "/v1/users"
                if (prefix.back() == '/' && !result.empty() && result[0] == '/') {
                    prefix.pop_back(); // 移除前缀末尾的斜杠
                }

                result = prefix + result;
            }

            return result;
        }

        /**
         * @brief 生成目标服务的完整URL
         * @param original_path 原始请求路径
         * @return 目标服务的完整URL，如 "http://user-service:8080/v1/users/123"
         *
         * @details URL生成过程：
         * 1. 路径重写：调用rewritePath()重写路径
         * 2. 协议添加：添加http://协议前缀
         * 3. 主机端口：添加目标主机和端口
         * 4. 路径拼接：拼接重写后的路径
         *
         * 示例：
         * - target_host: "user-service"
         * - target_port: 8080
         * - 重写路径: "/v1/users/123"
         * - 生成URL: "http://user-service:8080/v1/users/123"
         */
        std::string ServiceRoute::generateTargetUrl(const std::string &original_path) const {
            // 步骤1：重写路径
            std::string rewritten_path = rewritePath(original_path);

            // 步骤2：构建基础URL（协议 + 主机）
            std::string url = "http://" + target_host;

            // 步骤3：添加端口（如果不是默认的80端口）
            if (target_port != 80) {
                url += ":" + std::to_string(target_port);
            }

            // 步骤4：添加路径，确保路径格式正确
            if (rewritten_path.empty() || rewritten_path[0] != '/') {
                url += "/";  // 确保有根路径
            }
            url += rewritten_path;

            return url;
        }

        /**
         * @brief 添加新的服务路由
         * @param route 要添加的路由配置
         * @throws std::invalid_argument 如果路由配置无效
         *
         * @details 添加过程：
         * 1. 验证路由配置的有效性
         * 2. 获取写锁保证线程安全
         * 3. 检查是否存在同名服务路由
         * 4. 如果存在则更新，否则添加新路由
         *
         * 注意：使用服务名作为唯一标识，同名服务会被覆盖
         */
        void RouteManager::addRoute(const ServiceRoute &route) {
            LOG_DEBUG("RouteManager::addRoute - 开始添加路由: " + route.service_name);
            LOG_DEBUG("RouteManager::addRoute - 路由详情: path=" + route.path_pattern +
                     ", methods=[" + [&]() {
                         std::string methods_str;
                         for (size_t i = 0; i < route.methods.size(); ++i) {
                             if (i > 0) methods_str += ",";
                             methods_str += route.methods[i];
                         }
                         return methods_str;
                     }() + "], enabled=" + (route.enabled ? "true" : "false"));

            // 步骤1：验证路由配置
            if (!route.validate()) {
                LOG_ERROR("无效的路由配置: " + route.service_name);
                throw std::invalid_argument("无效的路由配置");
            }

            // 步骤2：获取写锁，确保线程安全
            std::unique_lock<std::shared_mutex> lock(routes_mutex_);

            // 步骤3：检查是否已存在同名服务路由
            auto it = std::find_if(routes_.begin(), routes_.end(),
                [&route](const ServiceRoute& existing) {
                    return existing.service_name == route.service_name;
                });

            // 步骤4：更新或添加路由
            if (it != routes_.end()) {
                // 存在同名服务，更新路由配置
                LOG_WARNING("服务路由已存在，将被更新: " + route.service_name);
                *it = route;
            } else {
                // 不存在，添加新路由
                routes_.push_back(route);
                LOG_INFO("添加服务路由: " + route.service_name + " -> " + route.path_pattern);
            }

            LOG_DEBUG("RouteManager::addRoute - 添加完成，当前路由总数: " + std::to_string(routes_.size()));
        }

        /**
         * @brief 移除指定服务的路由
         * @param service_name 要移除的服务名称
         *
         * @details 移除过程：
         * 1. 获取写锁保证线程安全
         * 2. 使用remove_if算法查找匹配的路由
         * 3. 删除找到的路由并记录日志
         *
         * 注意：会移除所有匹配服务名的路由
         */
        void RouteManager::removeRoute(const std::string &service_name) {
            // 获取写锁，确保线程安全
            std::unique_lock<std::shared_mutex> lock(routes_mutex_);

            // 使用remove_if算法查找并标记要删除的路由
            auto it = std::remove_if(routes_.begin(), routes_.end(),
                [&service_name](const ServiceRoute& route) {
                    return route.service_name == service_name;
                });

            // 如果找到匹配的路由，则删除
            if (it != routes_.end()) {
                routes_.erase(it, routes_.end());  // 删除标记的元素
                LOG_INFO("移除服务路由: " + service_name);
            } else {
                LOG_WARNING("服务路由不存在: " + service_name);
            }
        }

        void RouteManager::updateRoute(const ServiceRoute &route) {
            if (!route.validate()) {
                LOG_ERROR("无效的路由配置: " + route.service_name);
                throw std::invalid_argument("无效的路由配置");
            }

            std::unique_lock<std::shared_mutex> lock(routes_mutex_);

            auto it = std::find_if(routes_.begin(), routes_.end(),
                [&route](const ServiceRoute& existing) {
                    return existing.service_name == route.service_name;
                });

            if (it != routes_.end()) {
                *it = route;
                LOG_INFO("更新服务路由: " + route.service_name);
            } else {
                LOG_WARNING("服务路由不存在，将添加新路由: " + route.service_name);
                routes_.push_back(route);
            }
        }

        /**
         * @brief 查找匹配指定HTTP方法和路径的路由
         * @param method HTTP方法，如 "GET", "POST"
         * @param path 请求路径，如 "/api/users/123"
         * @return 匹配的路由对象指针，未找到返回nullptr
         *
         * @details 查找过程：
         * 1. 获取读锁保证线程安全
         * 2. 按照路由添加顺序遍历所有路由
         * 3. 检查路径匹配和HTTP方法支持
         * 4. 返回第一个匹配的路由
         *
         * 注意：返回第一个匹配的路由，因此路由顺序很重要
         */
        std::shared_ptr<ServiceRoute> RouteManager::findRoute(const std::string &method, const std::string &path) const {
            // 获取读锁，允许并发读取
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);

            LOG_DEBUG("RouteManager::findRoute - 查找路由: " + method + " " + path);
            LOG_DEBUG("RouteManager::findRoute - 当前路由总数: " + std::to_string(routes_.size()));

            // 按照添加顺序查找匹配的路由（优先级高的先匹配）
            for (size_t i = 0; i < routes_.size(); ++i) {
                const auto& route = routes_[i];
                LOG_DEBUG("RouteManager::findRoute - 检查路由[" + std::to_string(i) + "]: " +
                         route.service_name + " " + route.path_pattern);

                bool path_match = route.matchPath(path);
                bool method_match = route.supportMethod(method);

                LOG_DEBUG("RouteManager::findRoute - 路径匹配: " + std::string(path_match ? "是" : "否") +
                         ", 方法匹配: " + std::string(method_match ? "是" : "否"));

                // 检查路径匹配和HTTP方法支持
                if (path_match && method_match) {
                    LOG_DEBUG("找到匹配路由: " + method + " " + path + " -> " + route.service_name);
                    return std::make_shared<ServiceRoute>(route);
                }
            }

            // 未找到匹配的路由
            LOG_DEBUG("未找到匹配路由: " + method + " " + path);
            return nullptr;
        }

        std::vector<ServiceRoute> RouteManager::getAllRoutes() const {
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);
            return routes_;
        }

        void RouteManager::clear() {
            std::unique_lock<std::shared_mutex> lock(routes_mutex_);
            routes_.clear();
            LOG_INFO("清空所有路由");
        }

        std::shared_ptr<ServiceRoute> RouteManager::findRouteById(const std::string &route_id) const {
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);

            auto it = std::find_if(routes_.begin(), routes_.end(),
                [&route_id](const ServiceRoute& route) {
                    return route.route_id == route_id;
                });

            if (it != routes_.end()) {
                return std::make_shared<ServiceRoute>(*it);
            }

            return nullptr;
        }

        std::vector<ServiceRoute> RouteManager::getRoutesByService(const std::string &service_name) const {
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);

            std::vector<ServiceRoute> result;
            for (const auto& route : routes_) {
                if (route.service_name == service_name) {
                    result.push_back(route);
                }
            }

            return result;
        }

        bool RouteManager::setRouteEnabled(const std::string &route_id, bool enabled) {
            std::unique_lock<std::shared_mutex> lock(routes_mutex_);

            auto it = std::find_if(routes_.begin(), routes_.end(),
                [&route_id](ServiceRoute& route) {
                    return route.route_id == route_id;
                });

            if (it != routes_.end()) {
                it->enabled = enabled;
                LOG_INFO("路由状态更新: " + route_id + " -> " + (enabled ? "启用" : "禁用"));
                return true;
            }

            LOG_WARNING("路由不存在: " + route_id);
            return false;
        }

        size_t RouteManager::getRouteCount() const {
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);
            return routes_.size();
        }

        size_t RouteManager::getEnabledRouteCount() const {
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);

            return std::count_if(routes_.begin(), routes_.end(),
                [](const ServiceRoute& route) {
                    return route.enabled;
                });
        }

        std::vector<std::string> RouteManager::validateAllRoutes() const {
            std::shared_lock<std::shared_mutex> lock(routes_mutex_);

            std::vector<std::string> invalid_routes;
            for (const auto& route : routes_) {
                if (!route.validate()) {
                    invalid_routes.push_back(route.route_id);
                }
            }

            return invalid_routes;
        }

        /**
         * @brief 从配置文件加载路由规则
         * @param config_file 配置文件路径，支持YAML、JSON、ENV格式
         * @return 加载成功返回true，失败返回false
         *
         * @details 配置加载流程：
         * 1. 加载配置文件（自动识别格式）
         * 2. 清空现有路由配置
         * 3. 解析路由配置项
         * 4. 验证路由配置有效性
         * 5. 排序路由确保匹配优先级
         * 6. 可选启用热重载功能
         *
         * 支持的配置格式示例：
         *
         * YAML格式:
         * ```yaml
         * routes:
         *   user_route:
         *     path: "/api/users/*"
         *     service: "user-service"
         *     target_host: "user-service"
         *     target_port: 8080
         *     methods: "GET,POST,PUT,DELETE"
         *     timeout_ms: 30000
         *     retry_count: 3
         *     strip_path_prefix: true
         *     target_path_prefix: "/v1"
         *     match_type: "prefix"
         *     priority: 100
         *     enabled: true
         * ```
         *
         * JSON格式:
         * ```json
         * {
         *   "routes": {
         *     "user_route": {
         *       "path": "/api/users/*",
         *       "service": "user-service",
         *       "target_host": "user-service",
         *       "target_port": 8080,
         *       "methods": "GET,POST,PUT,DELETE",
         *       "timeout_ms": 30000,
         *       "retry_count": 3,
         *       "strip_path_prefix": true,
         *       "target_path_prefix": "/v1",
         *       "match_type": "prefix",
         *       "priority": 100,
         *       "enabled": true
         *     }
         *   }
         * }
         * ```
         */
        bool RouteManager::loadFromConfig(const std::string &config_file) {
            try {
                // 步骤1：加载配置文件（支持YAML和JSON格式）
                auto& config_manager = common::config::ConfigManager::getInstance();
                if (!config_manager.loadFromFile(config_file)) {
                    LOG_ERROR("无法加载配置文件: " + config_file);
                    return false;
                }

                // 步骤2：获取写锁，清空现有路由
                std::unique_lock<std::shared_mutex> lock(routes_mutex_);
                size_t old_route_count = routes_.size();
                routes_.clear();

                // 步骤3：获取路由配置的前缀映射
                auto route_configs = config_manager.getConfigsByPrefix("routes.");
                if (route_configs.empty()) {
                    LOG_WARNING("配置文件中未找到routes配置，使用空路由配置");
                    return true;
                }

                // 步骤4：解析路由配置
                size_t loaded_count = 0;
                std::map<std::string, ServiceRoute> route_map; // 使用路由名称作为键，支持多属性配置

                // 遍历所有路由相关的配置项
                for (const auto& [config_key, config_value] : route_configs) {
                    try {
                        // 解析配置键，提取路由名称和属性
                        // 配置键格式: "routes.{route_name}.{attribute}"
                        // 例如: "routes.user_route.path" -> 路由名称"user_route", 属性"path"
                        //      "routes.user_route.target_host" -> 路由名称"user_route", 属性"target_host"
                        auto [route_name, attribute] = parseConfigKey(config_key);

                        if (route_name.empty()) {
                            LOG_WARNING("无效的路由配置键: " + config_key);
                            continue;
                        }

                        // 确保路由对象存在（延迟创建）
                        // 如果是第一次遇到这个路由名称，创建新的ServiceRoute对象
                        if (route_map.find(route_name) == route_map.end()) {
                            route_map[route_name] = ServiceRoute{};
                        }

                        // 设置路由属性
                        // 根据属性名称和值，设置ServiceRoute对象的相应字段
                        setRouteAttribute(route_map[route_name], attribute, config_value);

                    } catch (const std::exception& e) {
                        LOG_ERROR("解析路由配置失败: " + config_key + " = " + config_value +
                                 " - " + std::string(e.what()));
                        continue; // 跳过错误的配置项，继续处理其他配置
                    }
                }

                // 步骤5：验证并添加路由
                for (auto& [route_name, route] : route_map) {
                    try {
                        // 验证路由配置的有效性
                        // 检查必需字段：path_pattern, service_name, target_host等
                        if (validateRoute(route)) {
                            routes_.push_back(std::move(route));
                            loaded_count++;

                            // 记录成功加载的路由详情
                            // LOG_DEBUG("加载路由规则[" + route_name + "]: " +
                            //          route.path_pattern + " -> " + route.service_name +
                            //          "(" + route.target_host + ":" + std::to_string(route.target_port) + ")");
                        } else {
                            // 跳过无效的路由配置
                            LOG_WARNING("跳过无效的路由配置[" + route_name + "]: " + route.path_pattern);
                        }

                    } catch (const std::exception& e) {
                        LOG_ERROR("验证路由配置失败[" + route_name + "]: " + std::string(e.what()));
                        continue; // 跳过错误的路由，继续处理其他路由
                    }
                }

                // 步骤6：对路由进行排序，确保匹配优先级正确
                // 按照优先级（priority）和路径特异性排序
                // 优先级高的路由先匹配，相同优先级时精确匹配优先于前缀匹配
                sortRoutes();

                // 步骤7：记录加载结果
                LOG_INFO("路由配置加载完成: " + config_file +
                        " (原有: " + std::to_string(old_route_count) +
                        ", 新加载: " + std::to_string(loaded_count) + ")");

                // 步骤8：启用配置热重载（可选）
                if (config_manager.get<bool>("routes.hot_reload.enabled", false)) {
                    auto check_interval = std::chrono::seconds(
                        config_manager.get<int>("routes.hot_reload.check_interval", 30)
                    );
                    config_manager.enableHotReload(config_file, check_interval);
                    LOG_INFO("已启用路由配置热重载，检查间隔: " + std::to_string(check_interval.count()) + "秒");
                }

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("加载路由配置失败: " + config_file + " - " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 解析配置键，提取路由名称和属性名
         * @param config_key 配置键，格式为"routes.{route_name}.{attribute}"
         * @return 返回{路由名称, 属性名}的pair，解析失败返回{"", ""}
         *
         * @details 解析示例：
         * - "routes.user_route.path" -> {"user_route", "path"}
         * - "routes.order_service.target_host" -> {"order_service", "target_host"}
         * - "routes.api.methods" -> {"api", "methods"}
         * - "invalid.key" -> {"", ""}
         *
         * 配置键必须至少包含3个部分，且第一部分必须是"routes"
         */
        std::pair<std::string, std::string> RouteManager::parseConfigKey(const std::string& config_key) {
            // 按点号分割配置键
            std::vector<std::string> parts;
            std::stringstream ss(config_key);
            std::string part;

            // 使用点号作为分隔符分割字符串
            while (std::getline(ss, part, '.')) {
                parts.push_back(part);
            }

            // 验证配置键格式：必须至少有3部分，且第一部分是"routes"
            // 格式：routes.{route_name}.{attribute}[.{sub_attribute}]
            if (parts.size() >= 3 && parts[0] == "routes") {
                return {parts[1], parts[2]}; // 返回路由名称和属性名
            }

            // 格式不正确，返回空字符串
            return {"", ""};
        }

        /**
         * @brief 设置路由对象的属性值
         * @param route 要设置的路由对象引用
         * @param attribute 属性名称，如"path", "service", "target_host"等
         * @param value 属性值的字符串表示
         *
         * @details 支持的属性及其格式：
         *
         * 基本路由属性：
         * - path: 路径模式，如"/api/users/*"
         * - service: 服务名称，如"user-service"
         * - methods: HTTP方法，如"GET,POST,PUT"
         *
         * 目标服务配置：
         * - target_host: 目标主机，如"user-service"
         * - target_port: 目标端口，如"8080"
         * - target_path_prefix: 目标路径前缀，如"/v1"
         *
         * 路径处理：
         * - strip_path_prefix: 是否去除路径前缀，"true"/"false"
         * - match_type: 匹配类型，"exact"/"prefix"/"regex"
         *
         * 超时和重试：
         * - timeout_ms: 超时时间（毫秒），如"30000"
         * - timeout: 超时时间（秒），如"30"，会自动转换为毫秒
         * - retry_count: 重试次数，如"3"
         *
         * 功能开关：
         * - enable_circuit_breaker: 启用熔断器，"true"/"false"
         * - enable_rate_limiting: 启用限流，"true"/"false"
         * - enabled: 启用路由，"true"/"false"
         *
         * 优先级：
         * - priority: 路由优先级，数字越大优先级越高
         */
        void RouteManager::setRouteAttribute(ServiceRoute& route, const std::string& attribute, const std::string& value) {
            // 基本路由属性设置
            if (attribute == "path") {
                // 设置路径匹配模式，如"/api/users/*"
                route.path_pattern = value;
            } else if (attribute == "service") {
                // 设置服务名称，用于标识和日志
                route.service_name = value;
            } else if (attribute == "method" || attribute == "methods") {
                // 解析HTTP方法列表，支持逗号分隔，如"GET,POST,PUT"
                route.methods = parseHttpMethodsVector(value);
            }

            // 目标服务配置
            else if (attribute == "target_host") {
                // 设置目标服务主机名或IP
                route.target_host = value;
            } else if (attribute == "target_port") {
                // 设置目标服务端口，字符串转整数
                route.target_port = std::stoi(value);
            } else if (attribute == "target_path_prefix") {
                // 设置目标路径前缀，用于路径重写
                route.target_path_prefix = value;
            }

            // 路径处理配置
            else if (attribute == "strip_path_prefix") {
                // 设置是否去除路径前缀，支持"true"/"1"和"false"/"0"
                route.strip_path_prefix = (value == "true" || value == "1");
            } else if (attribute == "match_type") {
                // 解析匹配类型：exact/prefix/regex
                route.match_type = parseMatchType(value);
            }

            // 超时和重试配置
            else if (attribute == "timeout_ms" || attribute == "timeout") {
                // 处理超时配置，支持毫秒和秒两种单位
                int timeout_value = std::stoi(value);
                if (attribute == "timeout") {
                    timeout_value *= 1000; // 秒转换为毫秒
                }
                route.timeout_ms = timeout_value;
            } else if (attribute == "retry_count") {
                // 设置重试次数
                route.retry_count = std::stoi(value);
            }

            // 功能开关配置
            else if (attribute == "enable_circuit_breaker") {
                // 设置是否启用熔断器
                route.enable_circuit_breaker = (value == "true" || value == "1");
            } else if (attribute == "enable_rate_limiting") {
                // 设置是否启用限流
                route.enable_rate_limiting = (value == "true" || value == "1");
            }

            // 优先级配置
            else if (attribute == "priority") {
                // 设置路由优先级，数字越大优先级越高
                route.priority = std::stoi(value);
            } else if (attribute == "enabled") {
                route.enabled = (value == "true" || value == "1");
            } else if (attribute == "route_id") {
                route.route_id = value;
            } else if (attribute == "health_check_enabled") {
                route.health_check_enabled = (value == "true" || value == "1");
            } else if (attribute == "health_check_path") {
                route.health_check_path = value;
            } else if (attribute == "health_check_interval_ms" || attribute == "health_check_interval") {
                // 如果配置中是秒，转换为毫秒
                int interval_value = std::stoi(value);
                if (attribute == "health_check_interval") {
                    interval_value *= 1000; // 秒转毫秒
                }
                route.health_check_interval_ms = interval_value;
            } else if (attribute == "load_balancer_strategy") {
                route.load_balancer_strategy = value;
            } else if (attribute.find("headers_to_add.") == 0) {
                // 处理需要添加的请求头配置
                std::string header_name = attribute.substr(16); // 去掉"headers_to_add."前缀
                route.headers_to_add[header_name] = value;
            } else if (attribute == "headers_to_remove") {
                // 处理需要移除的请求头配置（逗号分隔）
                route.headers_to_remove = parseStringVector(value);
            } else {
                LOG_WARNING("未知的路由属性: " + attribute + " = " + value);
            }
        }

        /**
         * @brief 解析HTTP方法字符串为vector
         * @param methods_str 逗号分隔的HTTP方法字符串，如"GET,POST,PUT"
         * @return HTTP方法向量
         */
        std::vector<std::string> RouteManager::parseHttpMethodsVector(const std::string& methods_str) {
            std::vector<std::string> methods;
            std::istringstream iss(methods_str);
            std::string method;

            while (std::getline(iss, method, ',')) {
                // 去除空格
                method.erase(std::remove_if(method.begin(), method.end(), ::isspace), method.end());

                // 转换为大写
                std::transform(method.begin(), method.end(), method.begin(), ::toupper);

                // 验证HTTP方法
                if (method == "GET" || method == "POST" || method == "PUT" ||
                    method == "DELETE" || method == "PATCH" || method == "HEAD" || method == "OPTIONS") {
                    methods.push_back(method);
                } else {
                    LOG_WARNING("未知的HTTP方法: " + method);
                }
            }

            // 如果没有指定方法，默认支持GET
            if (methods.empty()) {
                methods.push_back("GET");
            }

            return methods;
        }

        /**
         * @brief 解析字符串向量（逗号分隔）
         * @param str 逗号分隔的字符串，如"header1,header2,header3"
         * @return 字符串向量
         */
        std::vector<std::string> RouteManager::parseStringVector(const std::string& str) {
            std::vector<std::string> result;
            std::istringstream iss(str);
            std::string item;

            while (std::getline(iss, item, ',')) {
                // 去除前后空格
                item.erase(0, item.find_first_not_of(" \t"));
                item.erase(item.find_last_not_of(" \t") + 1);

                if (!item.empty()) {
                    result.push_back(item);
                }
            }

            return result;
        }

        /**
         * @brief 解析匹配类型字符串
         * @param match_type_str 匹配类型字符串，如"exact"、"prefix"、"regex"
         * @return 匹配类型枚举
         */
        ServiceRoute::MatchType RouteManager::parseMatchType(const std::string& match_type_str) {
            std::string type = match_type_str;
            std::transform(type.begin(), type.end(), type.begin(), ::tolower);

            if (type == "exact") {
                return ServiceRoute::MatchType::EXACT;
            } else if (type == "prefix") {
                return ServiceRoute::MatchType::PREFIX;
            } else if (type == "regex") {
                return ServiceRoute::MatchType::REGEX;
            } else {
                LOG_WARNING("未知的匹配类型: " + match_type_str + "，使用默认类型 PREFIX");
                return ServiceRoute::MatchType::PREFIX;
            }
        }

        /**
         * @brief 验证路由配置的有效性
         * @param route 要验证的路由对象
         * @return 验证通过返回true，否则返回false
         */
        bool RouteManager::validateRoute(const ServiceRoute& route) {
            // 检查路径是否为空
            if (route.path_pattern.empty()) {
                LOG_ERROR("路由路径不能为空");
                return false;
            }

            // 检查路径是否以/开头
            if (route.path_pattern[0] != '/') {
                LOG_ERROR("路由路径必须以/开头: " + route.path_pattern);
                return false;
            }

            // 检查服务名是否为空
            if (route.service_name.empty()) {
                LOG_ERROR("服务名不能为空，路径: " + route.path_pattern);
                return false;
            }

            // 检查目标主机是否为空
            if (route.target_host.empty()) {
                LOG_ERROR("目标主机不能为空，路径: " + route.path_pattern);
                return false;
            }

            // 检查目标端口是否合理（1-65535）
            if (route.target_port < 1 || route.target_port > 65535) {
                LOG_ERROR("目标端口必须在1-65535之间，路径: " + route.path_pattern +
                         "，当前值: " + std::to_string(route.target_port));
                return false;
            }

            // 检查是否至少支持一种HTTP方法
            if (route.methods.empty()) {
                LOG_ERROR("路由必须至少支持一种HTTP方法，路径: " + route.path_pattern);
                return false;
            }

            // 检查超时时间是否合理（100ms-300s）
            if (route.timeout_ms < 100 || route.timeout_ms > 300000) {
                LOG_ERROR("超时时间必须在100ms-300s之间，路径: " + route.path_pattern +
                         "，当前值: " + std::to_string(route.timeout_ms) + "ms");
                return false;
            }

            // 检查重试次数是否合理（0-10次）
            if (route.retry_count < 0 || route.retry_count > 10) {
                LOG_ERROR("重试次数必须在0-10次之间，路径: " + route.path_pattern +
                         "，当前值: " + std::to_string(route.retry_count));
                return false;
            }

            // 检查健康检查间隔是否合理（1s-300s）
            if (route.health_check_enabled) {
                if (route.health_check_interval_ms < 1000 || route.health_check_interval_ms > 300000) {
                    LOG_ERROR("健康检查间隔必须在1s-300s之间，路径: " + route.path_pattern +
                             "，当前值: " + std::to_string(route.health_check_interval_ms) + "ms");
                    return false;
                }

                // 检查健康检查路径
                if (route.health_check_path.empty() || route.health_check_path[0] != '/') {
                    LOG_ERROR("健康检查路径必须以/开头且不能为空，路径: " + route.path_pattern +
                             "，健康检查路径: " + route.health_check_path);
                    return false;
                }
            }

            // 检查负载均衡策略
            if (route.load_balancer_strategy != "round_robin" &&
                route.load_balancer_strategy != "weighted_round_robin" &&
                route.load_balancer_strategy != "least_connections") {
                LOG_WARNING("未知的负载均衡策略: " + route.load_balancer_strategy +
                        "，路径: " + route.path_pattern + "，将使用默认策略 round_robin");
            }

            // 检查路由ID是否为空（如果为空则自动生成）
            if (route.route_id.empty()) {
                LOG_WARNING("路由ID为空，路径: " + route.path_pattern + "，建议设置唯一的路由ID");
            }

            return true;
        }

        bool RouteManager::saveToConfig(const std::string &config_file) const {
            try {
                // 获取文件扩展名
                std::string extension = getFileExtension(config_file);
                std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);

                std::shared_lock<std::shared_mutex> lock(routes_mutex_);

                if (extension == ".json") {
                    return saveToJsonConfig(config_file);
                } else if (extension == ".yml" || extension == ".yaml") {
                    return saveToYamlConfig(config_file);
                } else if (extension == ".env") {
                    return saveToEnvConfig(config_file);
                } else {
                    LOG_ERROR("不支持的配置文件格式: " + extension);
                    return false;
                }

            } catch (const std::exception& e) {
                LOG_ERROR("保存路由配置失败: " + std::string(e.what()));
                return false;
            }
        }

        void RouteManager::sortRoutes() {
            std::sort(routes_.begin(), routes_.end());
        }

        bool RouteManager::routeIdExists(const std::string &route_id) const {
            return std::any_of(routes_.begin(), routes_.end(),
                [&route_id](const ServiceRoute& route) {
                    return route.route_id == route_id;
                });
        }

        std::string RouteManager::getFileExtension(const std::string &filename) const {
            size_t dot_pos = filename.find_last_of('.');
            if (dot_pos != std::string::npos) {
                return filename.substr(dot_pos);
            }
            return "";
        }

        bool RouteManager::saveToJsonConfig(const std::string &config_file) const {
            std::ofstream file(config_file);
            if (!file.is_open()) {
                LOG_ERROR("无法打开JSON配置文件进行写入: " + config_file);
                return false;
            }

            try {
                file << "{\n";
                file << "  \"routes\": [\n";

                for (size_t i = 0; i < routes_.size(); ++i) {
                    const auto& route = routes_[i];
                    file << "    {\n";
                    file << "      \"service_name\": \"" << escapeJsonString(route.service_name) << "\",\n";
                    file << "      \"path_pattern\": \"" << escapeJsonString(route.path_pattern) << "\",\n";
                    file << "      \"target_host\": \"" << escapeJsonString(route.target_host) << "\",\n";
                    file << "      \"target_port\": " << route.target_port << ",\n";
                    file << "      \"target_path_prefix\": \"" << escapeJsonString(route.target_path_prefix) << "\",\n";
                    file << "      \"strip_path_prefix\": " << (route.strip_path_prefix ? "true" : "false") << ",\n";
                    file << "      \"timeout_ms\": " << route.timeout_ms << ",\n";
                    file << "      \"retry_count\": " << route.retry_count << ",\n";
                    file << "      \"enable_circuit_breaker\": " << (route.enable_circuit_breaker ? "true" : "false") << ",\n";
                    file << "      \"enable_rate_limiting\": " << (route.enable_rate_limiting ? "true" : "false") << ",\n";
                    file << "      \"enabled\": " << (route.enabled ? "true" : "false") << ",\n";
                    file << "      \"priority\": " << route.priority << ",\n";
                    file << "      \"match_type\": \"" << ServiceRoute::matchTypeToString(route.match_type) << "\",\n";
                    file << "      \"route_id\": \"" << escapeJsonString(route.route_id) << "\",\n";
                    file << "      \"health_check_enabled\": " << (route.health_check_enabled ? "true" : "false") << ",\n";
                    file << "      \"health_check_path\": \"" << escapeJsonString(route.health_check_path) << "\",\n";
                    file << "      \"health_check_interval_ms\": " << route.health_check_interval_ms << ",\n";
                    file << "      \"load_balancer_strategy\": \"" << escapeJsonString(route.load_balancer_strategy) << "\",\n";

                    // HTTP方法数组
                    file << "      \"methods\": [";
                    for (size_t j = 0; j < route.methods.size(); ++j) {
                        if (j > 0) file << ", ";
                        file << "\"" << escapeJsonString(route.methods[j]) << "\"";
                    }
                    file << "],\n";

                    // 请求头映射
                    file << "      \"headers_to_add\": {\n";
                    size_t header_count = 0;
                    for (const auto& header : route.headers_to_add) {
                        if (header_count > 0) file << ",\n";
                        file << "        \"" << escapeJsonString(header.first) << "\": \"" << escapeJsonString(header.second) << "\"";
                        header_count++;
                    }
                    file << "\n      },\n";

                    // 要移除的请求头数组
                    file << "      \"headers_to_remove\": [";
                    for (size_t j = 0; j < route.headers_to_remove.size(); ++j) {
                        if (j > 0) file << ", ";
                        file << "\"" << escapeJsonString(route.headers_to_remove[j]) << "\"";
                    }
                    file << "]\n";

                    file << "    }";
                    if (i < routes_.size() - 1) file << ",";
                    file << "\n";
                }

                file << "  ]\n";
                file << "}\n";

                file.close();
                LOG_INFO("保存路由配置到JSON文件: " + config_file);
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("保存JSON配置文件失败: " + std::string(e.what()));
                return false;
            }
        }

        bool RouteManager::saveToYamlConfig(const std::string &config_file) const {
            std::ofstream file(config_file);
            if (!file.is_open()) {
                LOG_ERROR("无法打开YAML配置文件进行写入: " + config_file);
                return false;
            }

            try {
                file << "# API网关路由配置文件\n";
                file << "# 生成时间: " << getCurrentTimestamp() << "\n\n";
                file << "routes:\n";

                for (const auto& route : routes_) {
                    file << "  - service_name: \"" << route.service_name << "\"\n";
                    file << "    path_pattern: \"" << route.path_pattern << "\"\n";
                    file << "    target_host: \"" << route.target_host << "\"\n";
                    file << "    target_port: " << route.target_port << "\n";
                    file << "    target_path_prefix: \"" << route.target_path_prefix << "\"\n";
                    file << "    strip_path_prefix: " << (route.strip_path_prefix ? "true" : "false") << "\n";
                    file << "    timeout_ms: " << route.timeout_ms << "\n";
                    file << "    retry_count: " << route.retry_count << "\n";
                    file << "    enable_circuit_breaker: " << (route.enable_circuit_breaker ? "true" : "false") << "\n";
                    file << "    enable_rate_limiting: " << (route.enable_rate_limiting ? "true" : "false") << "\n";
                    file << "    enabled: " << (route.enabled ? "true" : "false") << "\n";
                    file << "    priority: " << route.priority << "\n";
                    file << "    match_type: \"" << ServiceRoute::matchTypeToString(route.match_type) << "\"\n";
                    file << "    route_id: \"" << route.route_id << "\"\n";
                    file << "    health_check_enabled: " << (route.health_check_enabled ? "true" : "false") << "\n";
                    file << "    health_check_path: \"" << route.health_check_path << "\"\n";
                    file << "    health_check_interval_ms: " << route.health_check_interval_ms << "\n";
                    file << "    load_balancer_strategy: \"" << route.load_balancer_strategy << "\"\n";

                    // HTTP方法
                    if (!route.methods.empty()) {
                        file << "    methods:\n";
                        for (const auto& method : route.methods) {
                            file << "      - \"" << method << "\"\n";
                        }
                    }

                    // 要添加的请求头
                    if (!route.headers_to_add.empty()) {
                        file << "    headers_to_add:\n";
                        for (const auto& header : route.headers_to_add) {
                            file << "      \"" << header.first << "\": \"" << header.second << "\"\n";
                        }
                    }

                    // 要移除的请求头
                    if (!route.headers_to_remove.empty()) {
                        file << "    headers_to_remove:\n";
                        for (const auto& header : route.headers_to_remove) {
                            file << "      - \"" << header << "\"\n";
                        }
                    }

                    file << "\n";
                }

                file.close();
                LOG_INFO("保存路由配置到YAML文件: " + config_file);
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("保存YAML配置文件失败: " + std::string(e.what()));
                return false;
            }
        }

        bool RouteManager::saveToEnvConfig(const std::string &config_file) const {
            std::ofstream file(config_file);
            if (!file.is_open()) {
                LOG_ERROR("无法打开ENV配置文件进行写入: " + config_file);
                return false;
            }

            try {
                file << "# API网关路由配置文件 (ENV格式)\n";
                file << "# 生成时间: " << getCurrentTimestamp() << "\n\n";

                for (size_t i = 0; i < routes_.size(); ++i) {
                    const auto& route = routes_[i];
                    std::string prefix = "ROUTE_" + std::to_string(i) + "_";

                    file << "# 路由 " << (i + 1) << ": " << route.service_name << "\n";
                    file << prefix << "SERVICE_NAME=\"" << route.service_name << "\"\n";
                    file << prefix << "PATH_PATTERN=\"" << route.path_pattern << "\"\n";
                    file << prefix << "TARGET_HOST=\"" << route.target_host << "\"\n";
                    file << prefix << "TARGET_PORT=" << route.target_port << "\n";
                    file << prefix << "TARGET_PATH_PREFIX=\"" << route.target_path_prefix << "\"\n";
                    file << prefix << "STRIP_PATH_PREFIX=" << (route.strip_path_prefix ? "true" : "false") << "\n";
                    file << prefix << "TIMEOUT_MS=" << route.timeout_ms << "\n";
                    file << prefix << "RETRY_COUNT=" << route.retry_count << "\n";
                    file << prefix << "ENABLE_CIRCUIT_BREAKER=" << (route.enable_circuit_breaker ? "true" : "false") << "\n";
                    file << prefix << "ENABLE_RATE_LIMITING=" << (route.enable_rate_limiting ? "true" : "false") << "\n";
                    file << prefix << "ENABLED=" << (route.enabled ? "true" : "false") << "\n";
                    file << prefix << "PRIORITY=" << route.priority << "\n";
                    file << prefix << "MATCH_TYPE=\"" << ServiceRoute::matchTypeToString(route.match_type) << "\"\n";
                    file << prefix << "ROUTE_ID=\"" << route.route_id << "\"\n";
                    file << prefix << "HEALTH_CHECK_ENABLED=" << (route.health_check_enabled ? "true" : "false") << "\n";
                    file << prefix << "HEALTH_CHECK_PATH=\"" << route.health_check_path << "\"\n";
                    file << prefix << "HEALTH_CHECK_INTERVAL_MS=" << route.health_check_interval_ms << "\n";
                    file << prefix << "LOAD_BALANCER_STRATEGY=\"" << route.load_balancer_strategy << "\"\n";

                    // HTTP方法（逗号分隔）
                    if (!route.methods.empty()) {
                        file << prefix << "METHODS=\"";
                        for (size_t j = 0; j < route.methods.size(); ++j) {
                            if (j > 0) file << ",";
                            file << route.methods[j];
                        }
                        file << "\"\n";
                    }

                    // 要添加的请求头（JSON格式）
                    if (!route.headers_to_add.empty()) {
                        file << prefix << "HEADERS_TO_ADD=\"{";
                        size_t header_count = 0;
                        for (const auto& header : route.headers_to_add) {
                            if (header_count > 0) file << ",";
                            file << "\\\"" << header.first << "\\\":\\\"" << header.second << "\\\"";
                            header_count++;
                        }
                        file << "}\"\n";
                    }

                    // 要移除的请求头（逗号分隔）
                    if (!route.headers_to_remove.empty()) {
                        file << prefix << "HEADERS_TO_REMOVE=\"";
                        for (size_t j = 0; j < route.headers_to_remove.size(); ++j) {
                            if (j > 0) file << ",";
                            file << route.headers_to_remove[j];
                        }
                        file << "\"\n";
                    }

                    file << "\n";
                }

                file.close();
                LOG_INFO("保存路由配置到ENV文件: " + config_file);
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("保存ENV配置文件失败: " + std::string(e.what()));
                return false;
            }
        }

        std::string RouteManager::escapeJsonString(const std::string &str) const {
            std::string result;
            for (char c : str) {
                switch (c) {
                    case '"': result += "\\\""; break;
                    case '\\': result += "\\\\"; break;
                    case '\n': result += "\\n"; break;
                    case '\r': result += "\\r"; break;
                    case '\t': result += "\\t"; break;
                    default: result += c; break;
                }
            }
            return result;
        }

        /**
         * @brief 获取当前时间戳字符串
         * @return 格式化的时间戳字符串，格式为"YYYY-MM-DD HH:MM:SS"
         *
         * @details 用于配置文件的时间戳标记，便于追踪配置更新时间
         */
        std::string RouteManager::getCurrentTimestamp() const {
            auto now = std::chrono::system_clock::now();
            auto time_t = std::chrono::system_clock::to_time_t(now);
            std::stringstream ss;
            ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
            return ss.str();
        }

    } // namespace api_gateway
} // namespace core_services

/**
 * @file service_route.cpp 实现总结
 *
 * 本文件实现了API网关的核心路由功能，主要包括：
 *
 * 1. **路径匹配系统**：
 *    - 精确匹配：完全相同的路径
 *    - 前缀匹配：支持通配符和目录匹配
 *    - 正则匹配：支持复杂的路径模式
 *
 * 2. **路径重写机制**：
 *    - 前缀去除：去除匹配的路径前缀
 *    - 前缀添加：添加目标服务的路径前缀
 *    - URL生成：构建完整的目标服务URL
 *
 * 3. **路由管理系统**：
 *    - 线程安全的路由增删改查
 *    - 优先级排序和匹配
 *    - 配置热重载支持
 *
 * 4. **配置系统**：
 *    - 支持YAML、JSON、ENV多种格式
 *    - 灵活的配置键解析
 *    - 完整的配置验证
 *
 * 5. **性能优化**：
 *    - 读写锁支持并发访问
 *    - 高效的路由匹配算法
 *    - 内存友好的数据结构
 *
 * 该实现为API网关提供了强大而灵活的路由能力，支持复杂的微服务架构需求。
 */